package com.namo.ccharticle.controller;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.namo.ccharticle.entity.Article;
import com.namo.ccharticle.service.ArticleService;
import com.namo.cchcommon.api.CommonPage;
import com.namo.cchcommon.api.CommonResult;
import com.namo.cchcommon.api.ResultCode;
import com.namo.cchcommon.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author WangXin
 * @date 2021/5/15 14:49
 */
@RestController
@RequestMapping("/article")
@Slf4j
public class ArticleController {
    @Autowired
    Gson gson;

    @Autowired
    ArticleService articleService;

    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public CommonResult getArticleList(){
        return CommonResult.success(articleService.getArticleList());
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public CommonResult addArticle(@RequestBody String req){
        Article article = new Article();
        JsonObject jsonObject = gson.fromJson(req, JsonObject.class);
        return CommonResult.success(articleService.addArticle(jsonObject));
    }

    @RequestMapping(value = "/info",method = RequestMethod.GET)
    public CommonResult getArticleInfo(@RequestParam(value = "id",required = false) String id){
        if (id == null) {
            log.error("请求参数解析错误=>解析为空" );
            throw new ApiException(ResultCode.VALIDATE_FAILED);
        }
        log.info("文章查询成功=>"+id);
        return CommonResult.success( gson.fromJson(articleService.getArticleInfo(id),Object.class));
    }
}
